package updateinfoimpl

import (
	"fmt"
	"strings"

	"github.com/sirupsen/logrus"
	"github.com/xuri/excelize/v2"

	"cvevulner/cve-ddd/domain"
)

// NewUpdateInfoImpl creates a new instance of updateInfoImpl with the provided logger.
func NewUpdateInfoImpl(log *logrus.Entry) *updateInfoImpl {
	return &updateInfoImpl{
		log: log,
	}
}

type updateInfoImpl struct {
	log *logrus.Entry
}

func (impl updateInfoImpl) Generate(cves domain.CvesByVersion) (data []byte, err error) {
	excel, err := impl.initExcel()
	if err != nil {
		return
	}

	for index, cve := range cves {
		if err = excel.SetCellValue("cve_list", fmt.Sprintf("A%d", index+2), cve.CveNum); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("B%d", index+2), cve.ColdIssue.Number); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("C%d", index+2), cve.ColdIssue.Repo); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("D%d", index+2), cve.HotIssueNum); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("E%d", index+2), cve.OpeneulerScore); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("F%d", index+2), cve.CveVersion); err != nil {
			return
		}

		if err = excel.SetCellValue("cve_list", fmt.Sprintf("G%d", index+2), impl.generateAbi(cve)); err != nil {
			return
		}
	}

	buff, err := excel.WriteToBuffer()
	if err != nil {
		return
	}

	return buff.Bytes(), nil
}

func (impl updateInfoImpl) initExcel() (f *excelize.File, err error) {
	f = excelize.NewFile()
	index, _ := f.NewSheet("cve_list")
	f.SetActiveSheet(index)

	if err = f.SetCellValue("cve_list", "A1", "cve编号"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "B1", "issue编号"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "C1", "issue所属仓库"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "D1", "热补丁issue编号"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "E1", "score"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "F1", "version"); err != nil {
		return
	}
	if err = f.SetCellValue("cve_list", "G1", "abi是否变化"); err != nil {
		return
	}

	return
}

func (impl updateInfoImpl) generateAbi(cve domain.Cve) string {
	ret := "无"
	if cve.AbiVersion == "" {
		return ret
	}

	split := strings.Split(cve.AbiVersion, ",")
	if len(split) == 0 {
		return ret
	}

	for _, v := range split {
		split2 := strings.Split(v, ":")
		if len(split2) != 2 || split2[0] != cve.AffectedVersion[0] || split2[1] == "" {
			continue
		}

		return split2[1]
	}

	return ret
}
